<template>
  <view :class="classNames" :style="styles">
    <slot></slot>
  </view>
</template>

<script lang="ts">
import { computed, defineComponent, provide, reactive, toRefs } from "vue";
import context from "./context";

export default defineComponent({
  name: "Row",
  options: {
    // 虚拟化节点
    virtualHost: true,
  },
  props: {
    gutter: {
      type: [Number, Object, Array],
      default: 0,
    },
    justify: {
      type: String,
      default: "start",
    },
    align: {
      type: String,
      default: "start",
    },
    div: {
      type: Boolean,
    },
    wrap: {
      type: Boolean,
      default: true,
    },
  },

  setup(props) {
    const { gutter, align, justify, div, wrap } = toRefs(props);
    const prefixCls = "arco-row";
    const classNames = computed(() => {
      return {
        [`${prefixCls}`]: !div.value,
        [`${prefixCls}-nowrap`]: !wrap.value,
        [`${prefixCls}-align-${align.value}`]: align.value,
        [`${prefixCls}-justify-${justify.value}`]: justify.value,
      };
    });

    const propGutterHorizontal = computed(() =>
      Array.isArray(gutter.value) ? gutter.value[0] : gutter.value,
    );
    const propGutterVertical = computed(() =>
      Array.isArray(gutter.value) ? gutter.value[1] : 0,
    );

    const styles = computed(() => {
      const result: any = {};
      if (propGutterHorizontal.value) {
        const marginHorizontal = -propGutterHorizontal.value / 2;
        const marginVertical = -propGutterVertical.value / 2;
        if (marginHorizontal) {
          result.marginLeft = `${marginHorizontal}rpx`;
          result.marginRight = `${marginHorizontal}rpx`;
        }
        if (marginVertical) {
          result.marginTop = `${marginVertical}rpx`;
          result.marginBottom = `${marginVertical}rpx`;
        }
      }
      return result;
    });

    const resultGutter = computed<[number, number]>(() => [
      propGutterHorizontal.value,
      propGutterVertical.value,
    ]);

    provide(
      context.RowContextInjectionKey,
      reactive({
        gutter: resultGutter,
        div,
      }),
    );
    return {
      classNames,
      styles,
    };
  },
});
</script>

<style lang="scss" scoped>
.arco-row {
  display: flex;
  flex-flow: row wrap;
}
.arco-row-nowrap {
  flex-wrap: nowrap;
}
.arco-row-align-start {
  align-items: flex-start;
}
.arco-row-align-center {
  align-items: center;
}
.arco-row-align-end {
  align-items: flex-end;
}
.arco-row-justify-start {
  justify-content: flex-start;
}
.arco-row-justify-center {
  justify-content: center;
}
.arco-row-justify-end {
  justify-content: flex-end;
}
.arco-row-justify-space-around {
  justify-content: space-around;
}
.arco-row-justify-space-between {
  justify-content: space-between;
}
</style>
